<template>
  <div class="department-manage-root">
    <v-row>
      <v-col cols="12" md="4" class="pr-4">
        <v-card>
          <v-card-title class="d-flex justify-space-between align-center">
            <span>部门树</span>
            <v-btn
              variant="outlined"
              color="grey-darken-1"
              elevation="0"
              size="small"
              style="background:rgba(128,128,128,0.08);min-width:70px;"
              @click="onAddDepartment"
            >
              新增
            </v-btn>
          </v-card-title>
          <v-card-text>
            <TreeList
              :items="departmentTree"
              :selected-id="selectedId"
              id-field="deptId"
              label-field="deptName"
              @select="onDepartmentNodeClick"
            />
          </v-card-text>
        </v-card>
      </v-col>
      <v-col cols="12" md="8">
        <v-card v-if="departmentDetail" class="department-detail-card">
          <v-card-title class="d-flex justify-space-between align-center">
            <span class="detail-title">{{ departmentDetail.deptName }}</span>
            <div>
              <v-btn
                variant="outlined"
                color="grey-darken-1"
                elevation="0"
                size="small"
                style="background:rgba(128,128,128,0.08);min-width:70px;"
                @click="onEditDepartment"
              >编辑</v-btn>
              <v-btn
                variant="outlined"
                color="grey-darken-1"
                elevation="0"
                size="small"
                style="background:rgba(128,128,128,0.08);min-width:70px;margin-left:12px;"
                @click="showDeleteDialog = true"
              >删除</v-btn>
            </div>
          </v-card-title>
          <v-card-text>
            <v-row>
              <v-col cols="12" sm="6">
                <div class="detail-label">部门ID：</div>
                <div class="detail-value">{{ departmentDetail.deptId }}</div>
              </v-col>
              <v-col cols="12" sm="6">
                <div class="detail-label">上级ID：</div>
                <div class="detail-value">{{ departmentDetail.parentId || '-' }}</div>
              </v-col>
              <v-col cols="12" sm="6">
                <div class="detail-label">排序：</div>
                <div class="detail-value">{{ departmentDetail.sort }}</div>
              </v-col>
              <v-col cols="12" sm="6">
                <div class="detail-label">状态：</div>
                <div class="detail-value">
                  <v-chip :color="departmentDetail.status === 1 ? 'primary' : 'grey'" size="small" variant="elevated">
                    {{ departmentDetail.status === 1 ? '启用' : '停用' }}
                  </v-chip>
                </div>
              </v-col>
              <v-col cols="12" sm="6">
                <div class="detail-label">创建时间：</div>
                <div class="detail-value">{{ departmentDetail.createTime }}</div>
              </v-col>
              <v-col cols="12" sm="6">
                <div class="detail-label">更新时间：</div>
                <div class="detail-value">{{ departmentDetail.updateTime }}</div>
              </v-col>
            </v-row>
          </v-card-text>
        </v-card>
        <div v-if="departmentDetail" class="view-user-dept-btn-wrap">
          <v-btn
            variant="outlined"
            color="grey-darken-1"
            elevation="0"
            size="large"
            style="background:rgba(128,128,128,0.08);min-width:220px;font-size:18px;letter-spacing:2px;"
            @click="openUserDeptDialog"
          >
            查看用户-部门归属
          </v-btn>
        </div>
        <div v-else class="empty-detail">请选择左侧部门查看详情</div>
      </v-col>
    </v-row>

    <!-- 新增/编辑弹窗 -->
    <v-dialog v-model="showEditDialog" max-width="500px">
      <v-card>
        <v-card-title>{{ editMode === 'add' ? '新增部门' : '编辑部门' }}</v-card-title>
        <v-card-text>
          <v-form ref="editFormRef">
            <v-text-field v-model="editForm.deptName" label="部门名称" required />
            <v-select
              v-model="editForm.parentId"
              :items="parentOptions"
              item-title="deptName"
              item-value="deptId"
              label="上级部门"
              clearable
            />
            <v-text-field v-model.number="editForm.sort" label="排序" type="number" />
            <v-select v-model="editForm.status" :items="statusOptions" label="状态" />
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="showEditDialog = false">取消</v-btn>
          <v-btn color="primary" @click="onSaveDepartment">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <!-- 删除确认弹窗 -->
    <v-dialog v-model="showDeleteDialog" max-width="400px">
      <v-card>
        <v-card-title>确认删除</v-card-title>
        <v-card-text>确定要删除该部门吗？此操作不可恢复。</v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="showDeleteDialog = false">取消</v-btn>
          <v-btn color="error" @click="onDeleteDepartment">删除</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
  <v-dialog v-model="showUserDeptDialog" max-width="1100px" @update:modelValue="val => showUserDeptDialog.value = val">
    <v-card>
      <v-card-title>用户-部门归属</v-card-title>
      <v-card-text style="max-height: 600px; overflow-y: auto;">
        <div>
          <template v-for="dept in departmentUserTree" :key="dept.deptId">
            <template v-for="item in flatDeptTree(dept, 0)" :key="item.dept.deptId">
              <v-card class="mb-3" outlined :style="{ marginLeft: (item.level * 32) + 'px', background: item.level === 0 ? '#f5f7fa' : '#fafbfc' }">
                <v-card-title style="font-weight:bold; color:#1976d2; font-size:16px;" class="d-flex justify-space-between align-center">
                  <div>
                    <span v-if="item.level > 0" style="font-size:13px; color:#888; margin-right:8px;">{{ '└'.padEnd(item.level+1, '─') }}</span>
                    {{ item.dept.deptName }}
                  </div>
                  <v-btn variant="outlined" color="grey-darken-1" elevation="0" size="small" style="background:rgba(128,128,128,0.08);min-width:70px;" @click="openAssignUserDialog(item.dept)">分配用户</v-btn>
                </v-card-title>
                <v-card-text>
                  <v-list density="compact">
                    <template v-if="Array.isArray(item.dept.hasUser) && item.dept.hasUser.length">
                      <v-list-item v-for="user in item.dept.hasUser" :key="user.id">
                        <v-list-item-content>
                          <v-list-item-title>{{ user.username }}</v-list-item-title>
                          <v-list-item-subtitle>
                            <span>邮箱：{{ user.email || '-' }}</span>｜<span>手机号：{{ user.phone || '-' }}</span>｜<span>状态：<span :style="{color: user.status === 1 ? '#1976d2' : '#888'}">{{ user.status === 1 ? '启用' : '停用' }}</span></span>
                          </v-list-item-subtitle>
                        </v-list-item-content>
                      </v-list-item>
                    </template>
                    <template v-else>
                      <v-list-item>
                        <v-list-item-content>
                          <v-list-item-title style="color:#aaa;">暂无用户</v-list-item-title>
                        </v-list-item-content>
                      </v-list-item>
                    </template>
                  </v-list>
                </v-card-text>
              </v-card>
            </template>
          </template>
        </div>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn variant="text" @click="showUserDeptDialog= false">关闭</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
  <v-dialog v-model="assignUserDialogVisible" max-width="500px">
    <v-card>
      <v-card-title>为{{ assignUserDeptName }}部门分配用户</v-card-title>
      <v-card-text>
        <v-select
          v-model="assignUserSelected.value"
          :items="assignUserList"
          item-title="username"
          item-value="id"
          label="选择用户"
          multiple
          chips
          clearable
        />
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn text @click="assignUserDialogVisible= false">取消</v-btn>
        <v-btn color="primary" @click="onAssignUserConfirm">保存</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch, defineProps } from 'vue'
import TreeList from './TreeList.vue'
import axios from 'axios'
import { API_BASE_URL } from '@/config/api'
import { getDepartmentUserTree, getAllUserList } from '@/api/index'
import { getUserTree, setUserDepartment } from '@/api/user'

const departmentTree = ref([])
const selectedId = ref(null)
const departmentDetail = ref(null)
const showEditDialog = ref(false)
const showDeleteDialog = ref(false)
const editMode = ref('add') // 'add' | 'edit'
const editForm = ref({})
const editFormRef = ref(null)
const showUserDeptDialog = ref(false)
const departmentUserTree = ref([])
const assignUserDialogVisible = ref(false)
const assignUserDeptId = ref('')
const assignUserDeptName = ref('')
const assignUserList = ref([])
const assignUserSelected = ref([])

const statusOptions = [
  { title: '启用', value: 1 },
  { title: '停用', value: 0 }
]

function flattenDepartments(tree) {
  let arr = []
  for (const node of tree) {
    arr.push(node)
    if (node.children && node.children.length) {
      arr = arr.concat(flattenDepartments(node.children))
    }
  }
  return arr
}
const parentOptions = computed(() => flattenDepartments(departmentTree.value).filter(d => !selectedId.value || d.deptId !== selectedId.value))

function fixTreeChildren(nodes) {
  if (!Array.isArray(nodes)) return []
  return nodes.map(node => ({
    ...node,
    children: fixTreeChildren(node.children || [])
  }))
}

function loadDepartmentTree() {
  axios.get(`${API_BASE_URL}/actions/departmentManage/list`).then(res => {
    const raw = res.data.data || []
    departmentTree.value = fixTreeChildren(raw)
  })
}

function onDepartmentNodeClick(node) {
  selectedId.value = node.deptId
  axios.get(`${API_BASE_URL}/actions/departmentManage/getById`, { params: { deptId: node.deptId } }).then(res => {
    departmentDetail.value = res.data.data || null
  })
}

function onAddDepartment() {
  editMode.value = 'add'
  editForm.value = { deptName: '', parentId: '', sort: 0, status: 1 }
  showEditDialog.value = true
}

function onEditDepartment() {
  if (!departmentDetail.value) return
  editMode.value = 'edit'
  editForm.value = {
    deptId: departmentDetail.value.deptId,
    deptName: departmentDetail.value.deptName,
    parentId: departmentDetail.value.parentId,
    sort: departmentDetail.value.sort,
    status: departmentDetail.value.status
  }
  showEditDialog.value = true
}

function onSaveDepartment() {
  if (editMode.value === 'add') {
    // 随机生成5位ID
    const deptId = randomId(5)
    const data = {
      deptId,
      deptName: editForm.value.deptName,
      parentId: editForm.value.parentId,
      sort: editForm.value.sort,
      status: editForm.value.status,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }
    axios.post(`${API_BASE_URL}/actions/departmentManage/add`, data).then(() => {
      showEditDialog.value = false
      loadDepartmentTree()
      nextTick(() => {
        selectedId.value = deptId
        onDepartmentNodeClick({ deptId })
      })
    })
    return
  }
  // 编辑
  const data = {
    deptId: editForm.value.deptId,
    deptName: editForm.value.deptName,
    parentId: editForm.value.parentId,
    sort: editForm.value.sort,
    status: editForm.value.status,
    createTime: departmentDetail.value.createTime,
    updateTime: new Date().toISOString()
  }
  axios.post(`${API_BASE_URL}/actions/departmentManage/update`, data).then(() => {
    showEditDialog.value = false
    loadDepartmentTree()
    nextTick(() => {
      selectedId.value = data.deptId
      onDepartmentNodeClick({ deptId: data.deptId })
    })
  })
}

function onDeleteDepartment() {
  if (!departmentDetail.value) return
  axios.post(`${API_BASE_URL}/actions/departmentManage/delete`, { deptId: departmentDetail.value.deptId }).then(() => {
    showDeleteDialog.value = false
    departmentDetail.value = null
    loadDepartmentTree()
    selectedId.value = null
  })
}

function randomId(len = 5) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < len; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

function openUserDeptDialog() {
  console.log(1)
  showUserDeptDialog.value = true
  getDepartmentUserTree().then(res => {
    departmentUserTree.value = res.data.data || []

  })
}

onMounted(() => {
  loadDepartmentTree()
})

function flatDeptTree(root, level = 0) {
  const arr = []
  function walk(node, lvl) {
    arr.push({ dept: node, level: lvl })
    if (Array.isArray(node.children) && node.children.length) {
      node.children.forEach(child => walk(child, lvl + 1))
    }
  }
  walk(root, level)
  return arr
}

function openAssignUserDialog(dept) {
  assignUserDeptId.value = dept.deptId
  assignUserDeptName.value = dept.deptName
  getUserTree({ pageNum: 1, pageSize: 9999 }).then(res => {
    assignUserList.value = (res.data.list || []).map(u => ({ id: u.id, username: u.username }))
    assignUserSelected.value = []
    assignUserDialogVisible.value = true
  })
}

function onAssignUserConfirm() {
  const deptId = assignUserDeptId.value;
  const userIds = assignUserSelected.value;
  console.log("deptId:", deptId, "userIds:", userIds); // 确保数据正确
const userId=userIds.value;
console.log("userId:", userId, "userIds:", userIds);
  if (!deptId || !userId) {
    console.log("条件不满足，提前返回"); // 检查是否进入这里
    return;
  }



  console.log("准备发送请求，userId:", userId);
  setUserDepartment({ userId, departMentId: deptId }).then(() => {
    assignUserDialogVisible.value = false
    openUserDeptDialog() // 刷新部门用户树
  })
}
</script>

<style scoped>
.department-manage-root {
  padding: 32px;
  font-size: 18px;
}
.v-card {
  margin-bottom: 16px;
}
.department-detail-card {
  max-width: 600px;
  margin: 0 auto;
  margin-top: 32px;
  padding: 16px 0;
}
.detail-title {
  font-size: 22px;
  font-weight: bold;
  color: #1976d2;
  margin-bottom: 12px;
}
.detail-label {
  color: #888;
  font-size: 14px;
}
.detail-value {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
}
.empty-detail {
  color: #aaa;
  text-align: center;
  margin-top: 80px;
  font-size: 18px;
}
.view-user-dept-btn-wrap {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}
</style>
